import { parseTime } from '@/utils/index';

export function standardFormat(time, formatType = 'YYYY-MM-DD HH:mm:ss') {
  if (!time) return '';
  return moment.unix(time).format(formatType);
}

export function standardFormatNoHour(time, cformat = 'YYYY-MM-DD', placeholder = '') {
  if (!time) return placeholder;
  return moment.unix(time).format(cformat);
}

export function standardFormatMonth(time, formatType = 'YYYY-MM') {
  if (!time) return '';
  return moment.unix(time).format(formatType);
}

export function standardFormatTime(time, formatType = 'YYYYMMDD') {
  return moment(time).format(formatType);
}

export function format(time, cformat, isRangeFormat = false) {
  if (!time || time === '--') return '--';
  if (time.toString().indexOf('-') >= 0 && !isRangeFormat) {
    return time.replace(/-/g, '/');
  }
  let ptime = time;
  if (time) {
    ptime = time.toString().length === 10 ? Number(time) * 1000 : time;
  }
  // let parsedDate = moment.utc(`${ptime}`, "YYMMDDHHmmss")
  return moment(new Date(Number(ptime))).format(cformat);
}

export function parseUTCTime(time, cFormat = 'YYYY-MM-DD') {
  if (!time) return null;
  if (arguments.length === 0) {
    return null;
  }
  const issafariBrowser = /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent);
  if (!issafariBrowser) {
    return parseTime(time, cFormat);
  } else {
    const formatA = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
    let date;
    if (typeof time === 'object') {
      date = time;
    } else {
      if (('' + time).length === 10) time = parseInt(time) * 1000;
      date = new Date(time.replace('+0000', ''));
    }
    const formatObj = {
      y: date.getFullYear(),
      m: date.getMonth() + 1,
      d: date.getDate(),
      h: date.getHours(),
      i: date.getMinutes(),
      s: date.getSeconds(),
      a: date.getDay()
    };
    const time_str = formatA.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
      let value = formatObj[key];
      // Note: getDay() returns 0 on Sunday
      if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ]; }
      if (result.length > 0 && value < 10) {
        value = '0' + value;
      }
      return value || 0;
    });
    return time_str;
  }

  // return moment.utc('2016-05-03T22:15:01+02:00');
}
